package net.taviscaron.drivenotes.server.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Encryption tools, such as salt generating, md5 hash, etc
 * @author Andrei Senchuk
 */
public class EncryptionUtil {
    private static Log logger = LogFactory.getLog(EncryptionUtil.class);

    /** random */
    private static final Random rnd = new Random (System.currentTimeMillis ());

    /** default salt lenght (used by generateSalt() without arguments) */
    public static final int DEFAULT_SALT_LENGHT = 5;

    /**default hash algorithm */
    public static final String DEFAULT_HASH_ALGORITHM = "MD5";

    /** all possibles salt symbols */
    private static final char[] SALT_SYMBOLS = {
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
    };

    /**
     * Generate salt with default lenght
     * @return salt
     */
    public static String generateSalt () {
        return generateSalt (DEFAULT_SALT_LENGHT);
    }

    /**
     * Generate variable lenght salt
     * @param lenght salt lenght
     * @return salt
     */
    public static String generateSalt (int lenght) {
        if (lenght > 0) {
            char[] buffer = new char[lenght];

            synchronized (rnd) {
                for (int i = 0; i < lenght; i++) {
                    buffer[i] = SALT_SYMBOLS[rnd.nextInt (SALT_SYMBOLS.length)];
                }
            }

//            Random rnd = new Random (System.nanoTime ());
//            for (int i = 0; i < lenght; i++) {
//                buffer[i] = SALT_SYMBOLS[rnd.nextInt (SALT_SYMBOLS.length)];
//            }

            return new String (buffer);
        } else {
            throw new IllegalArgumentException ("salt lenght must be positive");
        }
    }

    /**
     * Calculate hash for password and salt with default digest algorithm
     * If default algorithm not found, hash will be calculated as
     * new String (password + salt).hashCode ()
     * @param password password
     * @param salt salt
     * @return hash as hex string
     */
    public static String calculateHash (String password, String salt) {
        try {
            return calculateHash (password, salt, DEFAULT_HASH_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            logger.warn ("digest algorithm `" + DEFAULT_HASH_ALGORITHM +
                    "` not found. Hash calculated as new String (password + salt).hashCode ()");
        }
        return Integer.toHexString (new String(password + salt).hashCode ());
    }

    /**
     * Calculate hash for password and salt with specific digest algorithm
     * @param password password
     * @param salt salt
     * @param algorithm digest algorithm
     * @return hash as hex string
     * @throws NoSuchAlgorithmException if algorithm not found
     */
    public static String calculateHash (String password, String salt, String algorithm)
            throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance (algorithm);

        /* message = password + salt (concatenate) */
        String message = password + salt;
        byte[] hash = md.digest (message.getBytes ());

        return byteArrayToHexString (hash);
    }

    /**
     * Create string representation of byte array with aling in 2 symbols.
     * If result string lenght is less than 32, string will be wilded to 32
     * symbols by zeros
     * @param data byte array
     * @return hex string representation of byte array
     */
    public static String byteArrayToHexString (byte[] data) {
        StringBuffer sb = new StringBuffer (new BigInteger(1, data).toString (16));

        while (sb.length () < 32 || sb.length () % 2 == 1) {
            sb.insert (0, "0");
        }

        return sb.toString ().toLowerCase ();
    }
}
